<template>
  <div class="panel center-bottom">
    <div class="content" ref="chartRef"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

// 区县产量数据 - 固定使用county1
const countyData = {
  early2022: 515.81258922, 
  early2023: 515.87815823, 
  early2024: 515.83568061, 
  late2022: 515.75418158, 
  late2023: 515.740001,   
  late2024: 515.63615529, 
  early2025: 515.696562767028809
};

// 生成固定区县1的数据
const generateData = () => {
  // 计算增长率并输出调试信息（改为千分比）
  const growth2022 = ((countyData.late2022 - countyData.early2022) / countyData.early2022 * 1000);
  const growth2023 = ((countyData.late2023 - countyData.early2023) / countyData.early2023 * 1000);
  const growth2024 = ((countyData.late2024 - countyData.early2024) / countyData.early2024 * 1000);
  
  console.log('增长率计算(千分比):', {
    2022: growth2022,
    2023: growth2023,
    2024: growth2024
  });

  // 转换为图表所需的数据格式
  const data = [
    {
      time: '2022年',
      actual: countyData.late2022, // 直接使用吨为单位
      predict: countyData.early2022,
      growth: parseFloat(growth2022.toFixed(1))
    },
    {
      time: '2023年',
      actual: countyData.late2023,
      predict: countyData.early2023,
      growth: parseFloat(growth2023.toFixed(1))
    },
    {
      time: '2024年',
      actual: countyData.late2024,
      predict: countyData.early2024,
      growth: parseFloat(growth2024.toFixed(1))
    },
    {
      time: '2025年',
      actual: null, // 2025年晚稻数据为空
      predict: countyData.early2025,
      growth: null
    }
  ];

  return data;
};

const initChart = () => {
  try {
    if (!chartRef.value) {
      console.error('图表容器未找到')
      return
    }

    // 确保容器有高度
    if (chartRef.value.clientHeight === 0) {
      console.error('图表容器高度为0')
      return
    }

    // 如果已经存在图表实例，先销毁
    if (chart) {
      chart.dispose()
    }

    // 确保容器可见
    if (chartRef.value.offsetParent === null) {
      console.error('图表容器不可见')
      return
    }

    chart = echarts.init(chartRef.value)
    const data = generateData()

    // 计算每个系列的最小值和最大值
    const yieldRange = getMinMax(data, 'actual')
    const growthRange = getMinMax(data, 'growth')

    const option = {
      tooltip: {
        trigger: 'axis',
        position: function (pt: any) {
          return [pt[0], '10%'];
        },
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(51, 255, 208, 0.3)',
        borderWidth: 1,
        padding: [8, 12],
        textStyle: {
          color: '#fff'
        },
        z: 9999,
        confine: true,  // 确保悬浮窗不会超出图表区域
        formatter: (params: any) => {
          let result = `<div style="font-size: 12px; color: #33ffd0; margin-bottom: 8px; font-weight: bold;">${params[0].axisValue}</div>`
          params.forEach((param: any) => {
            const color = param.color
            const name = param.seriesName
            const value = param.value
            
            // 跳过null值
            if (value === null || value === undefined) {
              return
            }
            
            const unit = name === '实际产量' ? '吨' : name === '预测产量' ? '吨' : '‰'
            const displayValue = name === '增长率' ? `${parseFloat(value).toFixed(1)}${unit}` : `${parseFloat(value).toFixed(1)}${unit}`
            
            result += `
              <div style="display: flex; align-items: center; margin: 4px 0;">
                <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${color}; margin-right: 8px;"></span>
                <span style="color: #fff; margin-right: 8px; min-width: 60px;">${name}</span>
                <span style="color: #33ffd0; display: flex; align-items: center; justify-content: center; min-width: 60px; font-weight: bold;">
                  ${displayValue}
                </span>
              </div>
            `
          })
          return result
        }
      },
      legend: {
        data: ['实际产量', '预测产量', '增长率'],
        textStyle: {
          color: '#33ffd0',
          fontSize: 12
        },
        top: -2,
        itemWidth: 10,
        itemHeight: 10,
        itemGap: 15,
        padding: [5, 0, 5, 0]
      },
      grid: {
        top: '10%',
        left: '5%',
        right: '5%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: data.map(item => item.time),
        axisLine: {
          lineStyle: {
            color: '#33ffd0',
            width: 1
          }
        },
        axisLabel: {
          color: '#33ffd0',
          fontSize: 10,
          margin: 8
        },
        axisTick: {
          show: false
        }
      },
      yAxis: [
        {
          type: 'value',
          position: 'left',
          min: function(value) {
            // 设置Y轴最小值为数据最小值的99.9%，增加数据差距的视觉效果
            return Math.floor(value.min * 0.999);
          },
          max: function(value) {
            // 设置Y轴最大值为数据最大值的100.1%，增加数据差距的视觉效果
            return Math.ceil(value.max * 1.001);
          },
          axisLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(51, 255, 208, 0.1)',
              type: 'dashed'
            }
          },
          axisTick: {
            show: false
          }
        },
        {
          type: 'value',
          position: 'right',
          min: function(value) {
            return Math.floor(value.min * 0.9);
          },
          max: function(value) {
            return Math.ceil(value.max * 1.1);
          },
          axisLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        }
      ],
      series: [
        {
          name: '实际产量',
          type: 'line',
          smooth: true,
          data: data.map(item => item.actual),
          itemStyle: {
            color: '#e74c3c',
            borderWidth: 0
          },
          lineStyle: {
            width: 2,
            shadowColor: 'rgba(231, 76, 60, 0.3)',
            shadowBlur: 10,
            shadowOffsetY: 5
          },
          symbol: 'circle',
          symbolSize: 6,
          emphasis: {
            itemStyle: {
              color: '#e74c3c',
              borderColor: '#fff',
              borderWidth: 2
            }
          }
        },
        {
          name: '预测产量',
          type: 'line',
          smooth: true,
          data: data.map(item => item.predict),
          itemStyle: {
            color: '#f39c12',
            borderWidth: 0
          },
          lineStyle: {
            width: 2,
            shadowColor: 'rgba(243, 156, 18, 0.3)',
            shadowBlur: 10,
            shadowOffsetY: 5
          },
          symbol: 'circle',
          symbolSize: 6,
          emphasis: {
            itemStyle: {
              color: '#f39c12',
              borderColor: '#fff',
              borderWidth: 2
            }
          }
        },
        {
          name: '增长率',
          type: 'line',
          smooth: true,
          yAxisIndex: 1,
          data: data.map(item => item.growth),
          itemStyle: {
            color: '#3498db',
            borderWidth: 0
          },
          lineStyle: {
            width: 2,
            shadowColor: 'rgba(52, 152, 219, 0.3)',
            shadowBlur: 10,
            shadowOffsetY: 5
          },
          symbol: 'circle',
          symbolSize: 6,
          emphasis: {
            itemStyle: {
              color: '#3498db',
              borderColor: '#fff',
              borderWidth: 2
            }
          }
        }
      ]
    }

    chart.setOption(option)
    console.log('图表初始化成功')
  } catch (error) {
    console.error('图表初始化失败:', error)
  }
}

// 计算每个系列的最小值和最大值
const getMinMax = (data: any[], key: string) => {
  const values = data.map(item => item[key]).filter(value => value !== null && value !== undefined)
  if (values.length === 0) {
    return { min: 0, max: 100 }
  }
  const min = Math.min(...values)
  const max = Math.max(...values)
  // 添加一些缓冲空间
  const range = max - min
  return {
    min: Math.floor(min - range * 0.1),
    max: Math.ceil(max + range * 0.1)
  }
}

let initTimeout: number | null = null

onMounted(async () => {
  // 延迟初始化，确保容器已经渲染
  initTimeout = window.setTimeout(() => {
    initChart()
  }, 300)

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    if (chart) {
      try {
        chart.resize()
      } catch (error) {
        console.error('调整图表大小失败:', error)
      }
    }
  })
})

onUnmounted(() => {
  if (initTimeout) {
    clearTimeout(initTimeout)
  }
  if (chart) {
    chart.dispose()
  }
})
</script>

<style scoped>
.panel {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.content {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}
</style>

